Shoes.setup do
  gem 'rest-client'
end

require 'openssl/ssl'
require 'rest_client'
require 'rexml/document'

class MiddletierInterface
  
  def initialize(url)
    @middletier_url = url
  end
  
  def user
    @username
  end
  
  def role
    if @site.nil? or @role.nil?
      'guest'
    else
      @role
    end
  end
  
  def user=(name)
    @username = name
    @site = nil
  end
  
  def password=(pwd)
    @password = pwd
    @site = nil
  end
  
  def graceful_rescue
    
    if @site.nil?
	  @site = RestClient::Resource.new @middletier_url, :user => @username, :password => @password
      resp = get_role
	  @role = resp[:status] == 200 ? resp[:entry] : nil
    end
    
    begin
      yield
    rescue RestClient::Exception => e
      {:status => e.http_code}
    rescue Exception => e
      #alert e
      {:status => 503} # Service Unavailable
    end    
  end
  
  def register_user(username, password)
    graceful_rescue do
      RestClient::post "https://guest:guest@#{@middletier_url[/https:\/\/(.*)/, 1]}/users", "<?xml version=\"1.0\"?><user name=\"#{username}\" password=\"#{password}\" />", :content_type => 'text/xml'
      {:status => 201}
    end
  end
  
  def get_role()
    graceful_rescue do
      role = @site["users/myrole"].get(:accept => 'text/xml')
      {:status => 200, :entry => role}
    end
  end
  
  def query_files(username_query, file_query)
    graceful_rescue do
      # array of file hash
      # file hash contains:
      #   name, owner, file id
      doc = REXML::Document.new @site["users/#{URI.escape username_query}/files/#{URI.escape file_query}"].get(:accept => 'text/xml')
      files = doc.elements.to_a('files/file').map {|f| {:id => f.attribute('id').to_s, :name => f.attribute('name').to_s, :owner => f.attribute('owner').to_s} }
      {:status => 200, :entry => files}
    end
  end
  
  def get_file(username, file_id)
    graceful_rescue do
      {:status => 200, :entry => @site["users/#{username}/files/#{file_id}"].get }
    end
  end
  
  def put_file(username, filename, file)
    graceful_rescue do
      @site["users/#{username}/files/#{filename}"].put file
      {:status => 201}
    end
  end
  
  def delete_file(username, file_id)
    graceful_rescue do
      @site["users/#{username}/files/#{file_id}"].delete
      {:status => 204}
    end
  end
  
  def auth?
    begin	  
      graceful_rescue do
        status = query_files("^guest", '.')[:status]
        status != 401 and status < 500
      end
    rescue Exception
      false
    end
  end

  def guest?
    @username == 'guest'
  end
end
